﻿#region << 文件说明 >>

/*----------------------------------------------------------------
 * 命名空间：Vampirewal.Core.WebApi
 * 唯一标识：c9f6a2e9-ecff-41cb-88ab-66b4878c0cda
 * 文件名：MiddlewarePipeline
 *
 * 创建者：杨程
 * 电子邮箱：235160615@qq.com
 * 创建时间：2023/10/8 12:59:17
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/

#endregion << 文件说明 >>

namespace Vampirewal.Core.WebApi;

/// <summary>
/// 中间件管道
/// </summary>
internal sealed class VampirewalMiddlewarePipeline
{
    private readonly IReadOnlyList<IVampirewalMiddleware> _middlewares;

    public VampirewalMiddlewarePipeline(IReadOnlyList<IVampirewalMiddleware> middlewares)
    {
        _middlewares = middlewares;
    }

    public Task InvokeAsync(HttpListenerContext context)
    {
        var index = -1;

        Func<Task>? nextMiddleware = null;
        nextMiddleware = () =>
        {
            index++;
            
            return index < _middlewares.Count ? _middlewares[index].InvokeAsync(context, nextMiddleware) : Task.CompletedTask;
        };

        return nextMiddleware();
    }
}